package com.sw.util;

import com.sw.pojo.USDT;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameter;
import org.web3j.protocol.core.RemoteCall;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.ClientTransactionManager;
import org.web3j.tx.Contract;
import rx.Observable;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

public class USDTapi {
    private static USDTapi uSDTapi = new USDTapi();

    String fromAddr = "0xf1295a0322FC9703f1D3Fb6b128a14E3Eb6F23c1";
    String contractAddr = "0xD022599FCA8Fd260b6CDe04C604024E7eb52f8e2";

    public static USDTapi getUSDTApi(){
        return uSDTapi;
    }

    private USDTapi() {
        this.fromAddr = fromAddr;
        this.contractAddr = contractAddr;
    }

    Web3j web3j = Web3j.build(new HttpService());
    ClientTransactionManager transactionManager = new ClientTransactionManager(web3j,
            fromAddr);
    //token是智能合约的实例对象
    USDT token = USDT.load(contractAddr, web3j, transactionManager,
            Contract.GAS_PRICE, Contract.GAS_LIMIT);

    public void USDTGetBalance(String address) {
        RemoteCall<BigInteger> balance = token.balanceOf(address);
        try {
            BigInteger bigInteger = balance.send();
            System.out.println(bigInteger);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    public List<USDT.TransferEventResponse> transferEventOb(BigInteger startBlock){
        Observable<USDT.TransferEventResponse> event = token.transferEventObservable(
                DefaultBlockParameter.valueOf(startBlock), DefaultBlockParameter.valueOf(startBlock));
        //只监听一个块上的合约事件
        List<USDT.TransferEventResponse> results = new ArrayList<>();
        event.subscribe(tx -> {
            results.add(tx);
        });
        return results;
    }
    
}
